#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "autoresp.h"
#include "list.h"

extern char *errstr;
extern int errln;

void nstratostr(char *arr, char *str, char *sep);

int main(int argc, char *argv[])
{
    FILE *dictfile = fopen("dictionary.txt", "r");
    char kvbuf[100];
    list_head *pos, *n, *spos, *sn;
    vardef *vdtmp;
    kvline *kvtmp;
    section *sectmp;
    DECL_SECT(root);
    INIT_LIST_HEAD(&root.lp);

    init_lists(dictfile, &root);

    printf(errstr, errln);

    puts("Contents...");

    list_for_each_safe(spos, sn, &root.lp)
    {
        sectmp = list_entry(spos, section, lp);
        printf("of section %s:\n", sectmp->name);
        list_for_each_safe(pos, n, &sectmp->vdlist->lp)
        {
            vdtmp = list_entry(pos, vardef, lp);
            printf("\t%s = %s\n", vdtmp->name, vdtmp->val);
            free_vardef(vdtmp);
            free(vdtmp);
        }

        list_for_each_safe(pos, n, &sectmp->kvlist->lp)
        {
            kvtmp = list_entry(pos, kvline, lp);
            nstratostr(kvtmp->keys, kvbuf, ":");
            printf("\t%s::", kvbuf);
            nstratostr(kvtmp->vals, kvbuf, ":");
            puts(kvbuf);
            free_kvline(kvtmp);
            free(kvtmp);
        }
        free_section(sectmp);
    }

    free_section(&root);
    return 0;
}

void nstratostr(char *arr, char *str, char *sep)
{
    char *cp;
    for(;; arr++, str++)
        if(!*arr)
            if(!*(arr + 1))
            {
                *str = 0;
                return;
            }
            else
            {
                for(cp = sep; *cp; cp++, str++)
                    *str = *cp;
                --str;
            }
        else if(*arr) *str = *arr;
}
